package ua.flatmap.util;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.net.URL;

/**
 * Created by IntelliJ IDEA.
 * User: Kostya
 * Date: 09.07.11
 * Time: 16:46
 */
public class AddressToCoordinatesRetriever {
    public static Double[] getCoordinates(String address) throws IOException, ParserConfigurationException, SAXException {
        if (address == null){
            return new Double[2];
        }
        address = address.replace(",", "+");
        address = address.replace(" ", "+");

        String fullAddress = address + "+Киев+Украина";
        System.out.println(fullAddress);

        URL url = new URL("http://maps.google.com/maps/geo?q=" + fullAddress + "&output=xml&key=ABQIAAAANGTAqDyDam_07aWkklK2NBSD41w" +
                "X8VhCBpuiDVjGbFNuXE31lhQB8Gkwy-wmYbmaHIbJtfnlR9I_9A");

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(url.openStream());
        doc.getDocumentElement().normalize();
        NodeList nl = doc.getElementsByTagName("code");
        Element n = (Element) nl.item(0);
        String st = n.getFirstChild().getNodeValue();

        if (st.equals("200")) {  // check status
            NodeList n2 = doc.getElementsByTagName("coordinates");
            Element nn = (Element) n2.item(0);
            String st1 = nn.getFirstChild().getNodeValue();
            String[] strCoordinates = st1.split(",");
            Double[] coordinates = new Double[2];
            coordinates[0]=new Double(strCoordinates[0]);
            coordinates[1]=new Double(strCoordinates[1]);
            return coordinates;
        } else {
            return new Double[2];
        }


    }
}
